'use strict';
var crypto = require('../libs/crypto')
//取num1~num2的随机数 取得到num1,num2
function rand(num1,num2){
  return parseInt(Math.random()*(num2-num1+1)+num1)
}
module.exports = function(sequelize, DataTypes) {

  var format = {
    name: {
      type: DataTypes.STRING(20),
      allowNull: false
    },
    nickName: {
      type: DataTypes.STRING(20),
      allowNull: false
    },
    pass: {
      type: DataTypes.STRING(128),
      allowNull: false
    },
    salt: {
      type: DataTypes.STRING(128),
      allowNull: false
    },
    code: {
      type: DataTypes.STRING(6),
      allowNull: false
    },
    avator: {
      type: DataTypes.STRING(200),
      defaultValue: 'uploads/users/defaut.jpg'
    },
    status: {
      type: DataTypes.INTEGER,
      defaultValue: 1 //1正常， 禁用
    },
    type: {
      type: DataTypes.INTEGER,
      defaultValue: 1001 //1000管理员，1001普通
    }
  }
  var User = sequelize.define('user', format, {
    freezeTableName: true,
    tableName: 't_admins',
    indexes: [
      {
        unique: true,
        fields: ['name']
      },
      {
        unique: true,
        fields: ['code']
      }
    ]
  })

  User.createUser = function (user, cb) {
    var salt = crypto.randomBytes()
    var password = crypto.hash(user.pass + salt)
    user.pass = password
    user.salt = salt
    user.code = crypto.randomBytes(16).substring(0, rand(4, 6))
    return this.create(user)
  }
  User.createPass = function (pass) {
    var salt = crypto.randomBytes()
    var password = crypto.hash(pass + salt)
    return {
      salt,
      password
    }
  }
  User.verify = function (pass, salt, ciphertext) {
    return crypto.hash(pass + salt) === ciphertext
  }
  User.check = async function (name, pass) {
    var user = await this.findOne({where: {name}})
    if (!user) return -1
    var cipher = crypto.hash(pass + user.salt)
    return cipher === user.pass ? 1 : 0
  }

  return User
}
